<template>
  <div class="dialog">
    <el-dialog
      :title="'关键字'+titleText"
      :visible.sync="showDialog"
      width="35%"
      top="0"
      :close-on-click-modal="false"
      @close="cancel"
    >
      <el-form
        ref="ruleForm"
        label-position="left"
        :model="formData"
        :rules="rules"
        class="el-form"
      >
        <el-form-item label="关键字名称：" class="w100p" prop="hitchKeywordName">
          <el-input
            v-model="formData.hitchKeywordName"
            clearable
            placeholder="请输入关键字名称"
          />
        </el-form-item>

        <el-form-item label="选择设备类型：" class="w100p" prop="equipmentTypeCode">
          <el-cascader
            v-model="formData.equipmentTypeCode"
            :props="defaultProps"
            :options="equipmentTypeList"
            :show-all-levels="false"
            clearable
            placeholder="请选择所属设备类型"
            @change="changeEquipmentTypeCode"
          />
        </el-form-item>
        <el-form-item
          label="所属设备型号："
          prop="equModelCode"
          class="w100p"
          required
        >
          <el-select v-model="formData.equModelCode" filterable clearable>
            <el-option
              v-for="item in equModelArr"
              :key="item.equModelCode"
              :label="item.modelName"
              :value="item.equModelCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" class="w100p" prop="description">
          <el-input
            v-model="formData.description"
            clearable
            :rows="2"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import faultKeyManageApi from "@/api/equip-repair-support/fault-key-manage";
import equipTypeApi from "@/api/equip-manage/equip-type/index";
import equipModelApi from "@/api/equip-manage/equip-model";

export default {
  name: '',
  components: { },
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    },
    // equModelArr: {
    //   type: [Array],
    //   default: () => {
    //     return []
    //   }
    // }
  },
  data() {
    return {
      formData: {},
      equModelArr: [],
      equipmentTypeList: [],
      defaultProps: {
        children: "childList",
        value: "equipmentTypeCode",
        label: "equipmentTypeName",
        emitPath: false,
        checkStrictly: true,
      },
      rules: {
        hitchKeywordName: [
          { required: true, message: "请输入关键字名称", trigger: ["change", "blur"] }
        ],
        equModelCode: [
          { required: true, message: "请选择设备型号", trigger: ["change", "blur"] }
        ]
      },
      showDialog: this.show
    };
  },

  watch: {
    show(v) {
      this.showDialog = v;
    },
    nowChanceStau(v) {
      if (v === 'add') {
        this.formData = {}
      }
      if (v === 'edit') {
        this.formData = this.editObject;
        if (!this.formData.equModelCode&&this.formData.equModelId) {
          let index = this.equModelArr.findIndex(item => item.modelName === this.formData.equModelName);
          if (index !== -1) {
            this.$set(this.formData, 'equModelCode', this.equModelArr[index].equModelCode)
          }
        }
      }
      this.$nextTick(() => {
        this.$refs['ruleForm']?.clearValidate();
      });
    }
  },
  created() {
  },
  mounted() {
    this.queryEquipmentType();
    this.queryEquipModel();
  },
  methods: {
    // 关联设备类型，根据父级查询子级
    queryEquipmentType() {
      // 获取数据
      equipTypeApi.queryTree({}).then((res) => {
        if (res.code === 1) {
          let data = res.data || [];
          this.equipmentTypeList = this.filterTreeKey(data, 'childList');

          // this.changeEquipmentTypeCode(this.equipmentTypeList[0].children);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 循环过滤树形数组
    filterTreeKey(arr, child) {
      let newArr = []
      newArr = arr?.map(item => {
        if (item[child]&&item[child].length > 0) {
          item = {
            ...item,
          [child]: this.filterTreeKey(
              item[child], child
            )
          }
        } else {
          delete item[child]
        }
        return item
      })
      newArr = newArr?.filter(item => item != null)
      return newArr
    },
    changeEquipmentTypeCode(e) {
      if (e) {
        equipModelApi.queryAllEquModel(e).then((res) => {
          this.loading = false;
          if (res.code === 1) {
            let data = res.data || [];
            this.equModelArr = [];
            for (var i in data) {
              this.equModelArr.push({
                modelName: data[i],
                equModelCode: i,
              });
            }
            this.$set(this.formData, 'equModelCode', '')
          } else {
            this.$message.error(res.msg);
            this.equModelArr = [];
          }
        });
      } else {
        this.queryEquipModel();
      }
    },
    // 设备型号
    queryEquipModel() {
      this.loading = false;
      let params = {
        page: 1,
        size: 1000,
      };
      // 获取数据
      equipModelApi.queryPageList(params).then((res) => {
        this.loading = false;
        if (res.code === 1) {
          let data = res.data || {};

          this.equModelArr = data.content || [];
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            faultKeyManageApi.edit(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success("修改成功！");
                this.close()
              } else {
                this.$message.error(res.msg);
              }
            });
          } else if (this.nowChanceStau === "add") {
            faultKeyManageApi.add(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.close()
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    close() {
      this.formData = {}
              this.$nextTick(() => {
        this.$refs['ruleForm']?.clearValidate();
      });
      this.$emit("closeDialog");
    },
    cancel() {
      this.formData = {}
              this.$nextTick(() => {
        this.$refs['ruleForm']?.clearValidate();
      });
      this.$emit("cancelDialog");
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
